"""报告查询API路由"""

import logging
from typing import Dict, Any

from fastapi import APIRouter, Body, HTTPException, Depends, Query
from pydantic import ValidationError

from ..schemas import (
    ReportMainQueryRequest,
    ReportMainQueryResponse,
    ErrorResponse,
    ErrorCode
)
from ..services.report_service import ReportService
from ..core.exceptions import MedicalReportAPIException


logger = logging.getLogger(__name__)

# 创建API路由
router = APIRouter(prefix="/api/v1/reports", tags=["报告查询"])


@router.post(
    "/main",
    response_model=ReportMainQueryResponse,
    summary="报告主信息查询",
    description="""
    查询报告主信息，可以使用一个接口查询检验和检查报告。

    ## 功能说明
    - 支持按就诊卡号、身份证号、住院号查询
    - 支持按患者类型（门诊/住院）筛选
    - 支持按时间范围查询
    - 支持按医院ID筛选
    - 返回报告列表，包含基本信息和状态

    ## 参数要求
    - **medical_card_number**: 就诊卡号（必填）
    - **id_card**: 身份证号（必填，18位）
    - **admission_number**: 住院号（可选）
    - **patient_type**: 患者类型（可选：1门诊，2住院）
    - **start_time**: 开始时间（必填，格式：yyyy-MM-dd HH:mm:ss）
    - **end_time**: 结束时间（必填，格式：yyyy-MM-dd HH:mm:ss）
    - **patient_name**: 就诊人姓名（必填）
    - **hospital_id**: 医院ID（可选，多个用逗号分隔）

    ## 返回说明
    - **success**: 接口调用是否成功
    - **msg**: 成功或错误消息
    - **code**: 返回代码（参考错误码对照表）
    - **data**: 响应数据
        - **patient_name**: 患者姓名
        - **report**: 报告列表
            - **hospital_id**: 医院ID
            - **id**: 报告唯一标识
            - **type**: 报告类型（0检验，1检查）
            - **time**: 报告时间
            - **doctor**: 审核医生
            - **item**: 项目名称
            - **special_types**: 特殊类型
            - **status**: 报告状态
            - **is_empty**: 是否敏感报告
            - **pdf_url**: PDF链接
    """,
    responses={
        200: {
            "description": "查询成功",
            "content": {
                "application/json": {
                    "example": {
                        "success": True,
                        "msg": "成功",
                        "code": "10001",
                        "data": {
                            "patient_name": "张之路",
                            "report": [
                                {
                                    "hospital_id": "253",
                                    "id": "1001",
                                    "type": "0",
                                    "time": "2018-02-01 18:20:20",
                                    "doctor": "王春霞",
                                    "item": "血常规",
                                    "special_types": "NucleicAcidSingleTesting",
                                    "status": "reviewed",
                                    "is_empty": "1",
                                    "pdf_url": "https://www.example.com/pdfReportxxxx"
                                }
                            ]
                        }
                    }
                }
            }
        },
        400: {
            "description": "参数错误",
            "content": {
                "application/json": {
                    "example": {
                        "success": False,
                        "msg": "身份证号不能为空",
                        "code": "60501",
                        "data": None
                    }
                }
            }
        },
        500: {
            "description": "系统错误",
            "content": {
                "application/json": {
                    "example": {
                        "success": False,
                        "msg": "系统错误",
                        "code": "10003",
                        "data": None
                    }
                }
            }
        }
    }
)
async def query_report_main_info(request: ReportMainQueryRequest) -> Dict[str, Any]:
    """
    报告主信息查询接口

    Args:
        request: 查询请求参数

    Returns:
        查询结果
    """
    try:
        logger.info(f"收到报告查询请求 - 患者: {request.patient_name}")

        # 调用服务层处理查询逻辑
        result = ReportService.query_reports(request)

        logger.info(f"报告查询完成 - 成功: {result['success']}, 消息: {result['msg']}")

        return result

    except ValidationError as e:
        logger.error(f"参数验证失败: {e}")
        return {
            "success": False,
            "msg": "参数格式错误",
            "code": ErrorCode.PARAMETER_INVALID,
            "data": None
        }

    except MedicalReportAPIException as e:
        logger.error(f"API异常: {e.message}")
        return {
            "success": False,
            "msg": e.message,
            "code": e.code,
            "data": e.data
        }

    except Exception as e:
        logger.error(f"查询报告异常: {str(e)}", exc_info=True)
        return {
            "success": False,
            "msg": "系统错误",
            "code": ErrorCode.SYSTEM_ERROR,
            "data": None
        }


@router.get(
    "/detail/{report_id}",
    summary="报告详情查询",
    description="根据报告ID查询报告详细信息",
    responses={
        200: {
            "description": "查询成功",
            "content": {
                "application/json": {
                    "example": {
                        "success": True,
                        "msg": "成功",
                        "code": "10001",
                        "data": {
                            "report_id": "RPT1001",
                            "patient_name": "张之路",
                            "patient_age": 45,
                            "patient_gender": "男",
                            "hospital_name": "山东省立医院",
                            "department": "内科",
                            "doctor": "王春霞",
                            "report_time": "2018-02-01 18:20:20",
                            "report_type": "检验报告",
                            "item": "血常规",
                            "results": [
                                {
                                    "item_name": "白细胞计数",
                                    "result": "6.5",
                                    "unit": "×10^9/L",
                                    "reference_range": "4.0-10.0",
                                    "status": "正常"
                                }
                            ],
                            "conclusion": "血常规检查结果基本正常",
                            "status": "已审核"
                        }
                    }
                }
            }
        }
    }
)
async def get_report_detail(report_id: str) -> Dict[str, Any]:
    """
    报告详情查询

    Args:
        report_id: 报告ID

    Returns:
        报告详情
    """
    try:
        logger.info(f"查询报告详情 - 报告ID: {report_id}")

        # 调用服务层获取报告详情
        report_detail = ReportService.get_report_detail(report_id)

        if not report_detail:
            return {
                "success": False,
                "msg": "报告不存在",
                "code": ErrorCode.NO_DATA,
                "data": None
            }

        return {
            "success": True,
            "msg": "成功",
            "code": ErrorCode.SUCCESS,
            "data": report_detail
        }

    except Exception as e:
        logger.error(f"查询报告详情异常: {str(e)}", exc_info=True)
        return {
            "success": False,
            "msg": "系统错误",
            "code": ErrorCode.SYSTEM_ERROR,
            "data": None
        }


@router.get(
    "/statistics",
    summary="报告统计查询",
    description="获取患者的报告统计信息",
    responses={
        200: {
            "description": "查询成功",
            "content": {
                "application/json": {
                    "example": {
                        "success": True,
                        "msg": "成功",
                        "code": "10001",
                        "data": {
                            "total_reports": 15,
                            "laboratory_reports": 10,
                            "examination_reports": 5,
                            "recent_report_time": "2018-02-01 18:20:20",
                            "abnormal_reports": 2,
                            "pending_reports": 1
                        }
                    }
                }
            }
        }
    }
)
async def get_report_statistics(
    patient_id: str = Query(..., description="患者ID"),
    start_time: str = Query(..., description="开始时间"),
    end_time: str = Query(..., description="结束时间")
) -> Dict[str, Any]:
    """
    报告统计查询

    Args:
        patient_id: 患者ID
        start_time: 开始时间
        end_time: 结束时间

    Returns:
        统计信息
    """
    try:
        logger.info(f"查询报告统计 - 患者: {patient_id}")

        # 调用服务层获取统计信息
        statistics = ReportService.get_report_statistics(patient_id, start_time, end_time)

        return {
            "success": True,
            "msg": "成功",
            "code": ErrorCode.SUCCESS,
            "data": statistics
        }

    except Exception as e:
        logger.error(f"查询报告统计异常: {str(e)}", exc_info=True)
        return {
            "success": False,
            "msg": "系统错误",
            "code": ErrorCode.SYSTEM_ERROR,
            "data": None
        }